package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.apache.catalina.session.StandardSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Object userLogin(@RequestBody User user, HttpServletRequest request) {
        HashMap<String,Object> map = new HashMap<>();
        User user1 = userService.selectByName(user.getUsername());
        if (user1 == null) {
            map.put("message","当前用户名不存在!");
            return map;
        }
        if (!user.getPassword().equals(user1.getPassword())) {
            map.put("message","当前用户名密码错误!");
            return map;
        }
        user.setUserId(user1.getUserId());

        HttpSession session = request.getSession(true);
        if (session != null) {
            session.setAttribute("user",user);
        }
        return map;
    }
}
